<template>
    <div class="home">
        <div class="content">
            <div id="map-container" style="width: 100%; height: 100vh">
                <div class="popup" ref="popup">
                    <popInfo
                        ref="popInfo"
                        @showYearTable="showComponentC"
                        @showRawData="showComponentD"
                        @showCrossData="showComponentE"
                    />
                    <!-- <point-pop ref="pointPop" /> -->
                </div>
                <timeline ref="timeline" v-show="showC" />
                <rawData ref="rawData" v-show="showD" />
                <crossData ref="crossData" v-show="showE" />
                <sampleMapTool :map="dzMap" @clearLayer="clearLayer" style=""></sampleMapTool>
            </div>
        </div>
    </div>
</template>

<script>
import dayjs from 'dayjs';
import DZMap from '../map/index.js';
import JSONData from '/src/map/新疆维吾尔自治区.json';
import Overlay from 'ol/Overlay';
import timeline from '../views/home/timeline.vue';
import rawData from '../views/home/raw-measurement-data.vue';
import crossData from '../views/home/cross-dating-data.vue';
import popInfo from './home/pop.vue';
import sampleMapTool from '../components/sampleMapTool.vue';
import ComprehensiveMonitorAlarm from './ComprehensiveMonitorAlarm/ComprehensiveMonitorAlarm.vue';
import { ImageStatic } from 'ol/source';
import { transformExtent } from 'ol/proj';
import { mapState } from 'vuex';
import { markRaw } from 'vue';
export default {
    name: 'HomeView',
    components: {
        popInfo,
        timeline,
        rawData,
        crossData,
        sampleMapTool,
        ComprehensiveMonitorAlarm,
    },
    data() {
        return {
            showC: false,
            showD: false,
            showE: false,
            topMenuActive: 0,
            popup: null,
            ylColor: '#0091ff',
            map: null,
            dzMap: null,
            gridData: null,
            vectorLayer: null,
            vectorSource: null,
            newInfo: [
                {
                    sequenceNumber: 'IDM0001',
                    code: 'IDM0001-GNS',
                    sampleCode: 'GNS',
                    sampleName: '巩乃斯林场林中',
                },
            ],
        };
    },
    computed: {
        ...mapState(['qxxxData', 'DailyRain', 'FacstGrid', 'FacstGridPicture']),
        shouldShowComponent() {
            return this.$route.path == '/';
        },
    },

    watch: {
        qxxxData: {
            handler(newData) {
                this.showQxyjPoint(newData);
            },
            deep: true,
        },
        DailyRain: {
            handler(newData) {
                this.showRainMap(newData);
            },
            deep: true,
        },
        FacstGrid: {
            handler(newData) {
                this.showGrid(newData);
            },
            deep: true,
        },
        FacstGridPicture: {
            handler(newData) {
                this.showGridPicture(newData);
            },
            deep: true,
        },
    },
    methods: {
        showComponentC() {
            // 先判断是否已经显示过并且当前处于隐藏状态
            if (!this.showC) {
                this.showC = true;
            }
            console.log(this.showC, '111111111111111111');
            if (this.$refs.timeline) {
                this.$refs.timeline.showtimeline();
            }
        },
        showComponentD() {
            // 先判断是否已经显示过并且当前处于隐藏状态
            if (!this.showD) {
                this.showD = true;
            }
            console.log(this.showD, '111111111111111111');
            if (this.$refs.rawData) {
                this.$refs.rawData.showRawData();
            }
        },
        showComponentE() {
            // 先判断是否已经显示过并且当前处于隐藏状态
            if (!this.showE) {
                this.showE = true;
            }
            console.log(this.showE, '111111111111111111');
            if (this.$refs.crossData) {
                this.$refs.crossData.showRawData();
            }
        },
        initMap() {
            this.dzMap = new DZMap('map-container');
            let features = this.dzMap.format.converGeoJsonToFeature(JSONData); //json转feature
            console.log(features);
            this.geom = features[0].getGeometry(); //获取geometry对象
            this.dzMap.layer.initLayer(this.geom);
            // this.boundaryLayer = this.dzMap.layer.createMaskLayer("行政区域遮罩图层"); //zindex为10
            // this.boundaryLayer.getSource().clear();
            this.dzMap.panTo([87, 43], 6);
            //将地图对象由vuex管理
            this.$store.commit('setMap', markRaw(this.dzMap));
        },
        addOverlay() {
            this.dzMap.map.on('click', event => {
                const feature = this.dzMap.map.forEachFeatureAtPixel(event.pixel, f => {
                    console.log(f, '@@@@@@@@@@@@@@@@@@@@@@@@@@', event);
                    return f;
                });
                if (feature) {
                    console.log(feature, '**********************');
                    if (feature.values_.markerInfo != undefined) {
                        console.log(this.newInfo, 'newInfo#######################');
                        console.log(feature.values_.markerInfo, '#######################');
                        this.pointInfo = feature.values_.markerInfo;
                        if (this.popup == null) {
                            let elPopup = this.$refs.popup;
                            this.popup = new Overlay({
                                element: elPopup,
                                position: null,
                                offset: [0, -8],
                                positioning: 'bottom-center',
                            });
                            this.dzMap.map.addOverlay(this.popup);
                        }
                        this.popup.setPosition(feature.values_.geometry.flatCoordinates);
                        this.popup.setPosition(feature.values_.geometry.flatCoordinates);
                        if (
                            !('reservoirName' in feature.values_.markerInfo) &&
                            !('stnm' in feature.values_.markerInfo)
                        ) {
                            console.log('val对象缺少必要的属性', feature.values_.markerInfo);

                            return; // 如果两个属性都没有，直接返回
                        }
                        // this.popup.setVisible(true);
                        this.dzMap.panTo(feature.values_.geometry.flatCoordinates, 5);
                        this.$refs.popInfo.updateStationInfo(feature.values_.markerInfo);
                        this.$refs.timeline.getStationInfo(feature.values_.markerInfo);
                        // 调用子组件的 showCard 方法以显示弹窗
                        if (this.$refs.popInfo) {
                            this.$refs.popInfo.showCard();
                        }
                    }
                }
            });
            // 创建Overlay
            let elPopup = this.$refs.popup;
            this.popup = new Overlay({
                element: elPopup,
                // 弹窗的定位位置，初始时可以设置为null，之后通过setPosition方法动态设置
                // position: null,
                offset: [0, -8],
                //弹窗定位-'top-left','top-right','bottom-left','bottom-right'
                positioning: 'bottom-center',
            });
            this.dzMap.map.addOverlay(this.popup);
        },
        showQxyjPoint(info) {
            // this.clearAllLayers();
            console.log(info, '1234567890');
            if (typeof info === 'undefined') {
                console.log('info is undefined');
                return;
            } else {
                //加点
                info.forEach(item => {
                    let legendType = '江河';
                    if (item.type == '河道站' && item.status_difference < 0) {
                        legendType = '江河';
                    } else if (item.type == '河道站' && item.status_difference >= 0) {
                        legendType = '超警戒站';
                    } else if (item.type == '水库站' && item.status_difference < 0) {
                        legendType = '水库站';
                    } else if (item.type == '水库站' && item.status_difference >= 0) {
                        legendType = '超汛限站';
                    }
                    this.dzMap.marker.addMarker(
                        item.lgtd || item.center[0],
                        item.lttd || item.center[1],
                        this.jcMakerLayer,
                        {
                            imgUrl: require(`../assets/lenged/${legendType}.png`),
                            scale: 1.5, //大小
                            radius: 15,
                            pBorderColor: '#000000',
                            pBorderWidth: 1,
                            pFillColor: '',
                        },
                        item
                    );
                });
            }
        },
        showRainMap(info) {
            // this.clearAllLayers();
            console.log(info, '12345678901111');
            if (info.length == 0) {
                return;
            }
            if (info[0].type == '隐患点') {
                //加点
                info.forEach(item => {
                    this.getylColor(info, item.arearain);
                    this.dzMap.marker.addMarker(
                        item.longitude || item.center[0],
                        item.latitude || item.center[1],
                        this.jcMakerLayer,
                        {
                            // imgUrl: require(`../assets/lenged/${legendType}.png`),
                            scale: 1.5, //大小
                            radius: 15,
                            pBorderColor: '#000000',
                            pBorderWidth: 1,
                            pFillColor: this.ylColor,
                        },
                        item
                    );
                });
            } else {
                //加面
                info.forEach(item => {
                    this.getylColor(info, item.arearain);
                    // console.log(color, '1234567890加面');
                    this.dzMap.polygon.addPolygon([item.basinPerimeterArray], this.DailyRainLayer, {
                        fillColor: this.ylColor,
                        strokeColor: this.ylColor,
                    });
                });
            }
            // //加点
            // info.forEach((item) => {
            //   this.dzMap.marker.addMarker(
            //     item.lgtd || item.center[0],
            //     item.lttd || item.center[1],
            //     this.jcMakerLayer,
            //     {
            //       // imgUrl: require(`../assets/images/header/point.png`),
            //       scale: 1.2, //大小
            //       radius: 15,
            //       pBorderColor: "#000000",
            //       pBorderWidth: 1,
            //       pFillColor: "",
            //     },
            //     item
            //   );
            // });
        },
        filterPointsByStep(points, numCols, step) {
            const filteredPoints = [];
            for (let i = 0; i < points.length; i++) {
                // 计算当前点的行索引和列索引
                const rowIndex = Math.floor(i / numCols);
                const colIndex = i % numCols;
                // 检查行索引和列索引是否都是步长的倍数
                if (rowIndex % step === 0 && colIndex % step === 0) {
                    filteredPoints.push(points[i]);
                }
            }
            return filteredPoints;
        },
        showGrid(info) {
            console.log(info, '1234567890');
            let color = '#000000';
            this.gridData = info.lons.map((lon, index) => {
                return {
                    lon: lon,
                    lat: info.lats[index],
                    value: info.vals[index],
                };
            });
            console.log(this.gridData, '1234567890gridData');
            this.gridData = this.filterPointsByStep(this.gridData, 450, 9);
            console.log(this.gridData, '1234567890gridData');
            this.gridData.forEach(item => {
                if (item.value !== -99999.0)
                    //属性值
                    this.dzMap.marker.addText([item.lon, item.lat], this.DailyRainLayer, {
                        name: `${item.value ? item.value : ''}`,
                        fillColor: color,
                        font: 'normal 12px 微软雅黑',
                        offsetX: 0,
                        offsetY: 0,
                    });
            });
        },
        showGridPicture(info) {
            console.log(info, '1234567890gridPicture1111111111111');

            // const imageLayer = new Image({
            //   name: "RiskZoing-layer",
            //   source: new ImageStatic({
            //     url: info,
            let imageExtent = transformExtent(
                [70.44696, 32.512374, 101.383751, 50.367755],
                'EPSG:4326',
                'EPSG:4326'
            );

            //   }),
            // });
            // imageLayer.setZIndex(20);
            // this.dzMap.map.addLayer(imageLayer);
            this.dzMap.layer.setImgLayer(info, imageExtent, '静态图片图层');
        },

        //获取不同类型格点的颜色
        getylColor(info, value) {
            console.log(info, 'colorinfo');
            this.ylColor = '';
            // value=Math.abs(value);
            // 首先对dailyRainList.colorRange数组根据elementvalue进行升序排序
            info[0].colorRange.sort((a, b) => a.elementvalue - b.elementvalue);
            // console.log(value ,"value");
            // 遍历排序后的数组
            for (let i = 0; i < info[0].colorRange.length - 1; i++) {
                // 如果value在当前元素的elementvalue和下一个元素的elementvalue之间
                if (
                    value >= info[0].colorRange[i].elementvalue &&
                    value < info[0].colorRange[i + 1].elementvalue
                ) {
                    // 返回当前元素的elementcolor
                    this.ylColor = `#${info[0].colorRange[i].elementcolor
                        .toString(16)
                        .padStart(6, '0')}`;
                }
            }
            // 如果value等于最大的elementvalue，返回最后一个元素的elementcolor
            if (value >= info[0].colorRange[info[0].colorRange.length - 1].elementvalue) {
                this.ylColor = '#000';
            }
            //如果value小于最小的elementvalue，返回第一个元素的elementcolor
            if (value < info[0].colorRange[0].elementvalue) {
                this.ylColor = '#000';
            }
            // console.log( this.ylColor,"ylColor");
        },
        creatAllLayers() {
            this.jcMakerLayer = this.dzMap.layer.createVectorLayer('点图层');
            this.DailyRainLayer = this.dzMap.layer.createVectorLayer('雨量图层');
            //创建点图层
            // this.yjJxhGridLayer = this.dzMap.layer.createWebGLPointsLayer(
            //     '精细化网格',
            //     this.GridColor
            // );
        },
        clearAllLayers() {
            this.jcMakerLayer.getSource().clear();
            this.DailyRainLayer.getSource().clear();
        },
        clearLayer() {
            this.dzMap.interaction.clearDraw();
            this.$refs.mapTool.tipVisable = false;
            // //清除站点
            // let yhdLayer = this.dzMap.layer.getLayerByName("隐患点图层");
            // let fxqLayer = this.dzMap.layer.getLayerByName("风险区图层");
            //清除图片
            yhdLayer.getSource().clear();
            fxqLayer.getSource().clear();
            // this.pointClearFlag=!this.pointClearFlag;
        },
    },

    mounted() {
        setInterval(() => {
            this.time = dayjs().format('HH:mm:ss');
        }, 1000);
        this.initMap();
        this.creatAllLayers();
        this.dzMap.layer.createAreaLineLayer(JSONData);
        this.showQxyjPoint([]);
        this.addOverlay();
    },
};
</script>

<style lang="scss" scoped>
.content {
    position: relative;
    top: -110px;
    display: flex;
    /* 根据需要调整这个值 */
}
#map-container {
    width: 100%;
    height: 100vh;
    position: absolute;
    // top: 70px; /* 假设导航栏高度为 110px */
}
</style>
